﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using ContactCenter.Core.DomainModel;
using ContactCenter.Core.Interfaces;
using ContactCenter.UI.Web.Models;

namespace ContactCenter.UI.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly ICustomerRepository _repository;
        //
        // GET: /Home/

        public HomeController(ICustomerRepository repository)
        {
            _repository = repository;
        }

        public ActionResult Index()
        {
            IEnumerable<Customer> customers = _repository.GetAll();
            
            IEnumerable<CustomerDTO> customerDtos = Mapper.Map<IEnumerable<Customer>, List<CustomerDTO>>(customers).AsEnumerable();
            
            return View(customerDtos);
        }       


        public ActionResult Edit(int id)
        {
            Customer customer = _repository.GetById(id);
            CustomerDTO customerDto = Mapper.Map<Customer, CustomerDTO>(customer);
            return View(customerDto);
        }

        [HttpPost]
        public ActionResult Edit(CustomerDTO customer)
        {
            //Customer cust = Mapper.Map<CustomerDTO,Customer>(customer);

            Customer oldCustomer = _repository.GetById(customer.Id);

            oldCustomer.ChangeCustomerName(customer.CustomerName);

            CreditCard newCreditCard = Mapper.Map<CreditCardDTO,CreditCard>(customer.CreditCard);
            oldCustomer.ChangeCreditCard(newCreditCard);

            //oldCustomer.RemoveAllAddresses();
            //foreach (Address address in oldCustomer.Addresses)
            //{
            //    oldCustomer.AddAddress(address);
            //}

            ContactInfo ci = Mapper.Map<ContactInfoDTO,ContactInfo>(customer.ContactInfo);
            oldCustomer.ChangeContactInfo(ci);

            _repository.Save(oldCustomer);
            return RedirectToAction("Index");
        }

        public ActionResult EditAddress()
        {
            throw new NotImplementedException();
        }
    }
}
